"""
批量添加任务对话框
"""
from PyQt6.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QLabel, 
                           QLineEdit, QRadioButton, QSpinBox, QPushButton,
                           QButtonGroup, QWidget, QMessageBox)
from PyQt6.QtCore import Qt
from com.db.task_manager import TaskManager
from datetime import datetime
import json

class BatchAddTaskDialog(QDialog):
    def __init__(self, selected_items=None, parent=None):
        super().__init__(parent)
        self.selected_items = selected_items or []
        self.task_manager = TaskManager()
        self.setup_ui()
        
    def setup_ui(self):
        """初始化UI"""
        self.setWindowTitle("批量添加任务")
        self.setMinimumWidth(400)
        
        layout = QVBoxLayout()
        layout.setSpacing(20)
        
        # 标签
        tag_label = QLabel("标签")
        self.tag_input = QLineEdit()
        self.tag_input.setPlaceholderText("请选择或输入标签")
        tag_hint = QLabel("可设置一个简单的标签方便后期识别和管理任务")
        tag_hint.setStyleSheet("color: #999999; font-size: 12px;")
        
        layout.addWidget(tag_label)
        layout.addWidget(self.tag_input)
        layout.addWidget(tag_hint)
        
        # 扫货数量
        scan_count_label = QLabel("扫货数量")
        scan_count_layout = QHBoxLayout()
        self.scan_count_spin = QSpinBox()
        self.scan_count_spin.setRange(1, 999)
        self.scan_count_spin.setValue(1)
        scan_count_hint = QLabel("最多限购数量，超过限额自动取消")
        scan_count_hint.setStyleSheet("color: #999999;")
        scan_count_layout.addWidget(self.scan_count_spin)
        scan_count_layout.addWidget(scan_count_hint)
        scan_count_layout.addStretch()
        
        layout.addWidget(scan_count_label)
        layout.addLayout(scan_count_layout)
        
        # 监控频率
        monitor_freq_label = QLabel("监控频率")
        monitor_freq_layout = QHBoxLayout()
        self.monitor_freq_label = QLabel("最快")
        self.monitor_freq_spin = QSpinBox()
        self.monitor_freq_spin.setRange(1, 999)
        self.monitor_freq_spin.setValue(10)
        monitor_freq_layout.addWidget(self.monitor_freq_label)
        monitor_freq_layout.addWidget(self.monitor_freq_spin)
        monitor_freq_layout.addWidget(QLabel("秒监控一次"))
        monitor_freq_layout.addStretch()
        
        layout.addWidget(monitor_freq_label)
        layout.addLayout(monitor_freq_layout)
        
        # 状态
        status_label = QLabel("状态")
        status_layout = QHBoxLayout()
        self.status_enabled = QRadioButton("启用")
        self.status_disabled = QRadioButton("禁用")
        self.status_enabled.setChecked(True)
        status_layout.addWidget(self.status_enabled)
        status_layout.addWidget(self.status_disabled)
        status_layout.addStretch()
        
        layout.addWidget(status_label)
        layout.addLayout(status_layout)
        
        # 按钮区域
        button_layout = QHBoxLayout()
        button_layout.addStretch()
        
        self.cancel_button = QPushButton("取消")
        self.confirm_button = QPushButton("确定")
        self.confirm_button.setDefault(True)
        
        button_layout.addWidget(self.cancel_button)
        button_layout.addWidget(self.confirm_button)
        
        layout.addStretch()
        layout.addLayout(button_layout)
        
        self.setLayout(layout)
        
        # 连接信号
        self.cancel_button.clicked.connect(self.reject)
        self.confirm_button.clicked.connect(self.save_tasks)
        
    def get_form_data(self):
        """获取表单数据"""
        return {
            'tag': self.tag_input.text(),
            'scan_count': self.scan_count_spin.value(),
            'monitor_freq': self.monitor_freq_spin.value(),
            'status': 1 if self.status_enabled.isChecked() else 0
        }

    def save_tasks(self):
        """保存任务到数据库，如果任务已存在（通过goods_id判断）则更新，否则新增"""
        try:
            form_data = self.get_form_data()
            current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            
            # 记录添加和更新的任务数量
            added_count = 0
            updated_count = 0
            
            # 批量添加任务
            for item in self.selected_items:
                try:
                    # 处理磨损值范围
                    wear_range = item.get('wear', '0-1').split('-')
                    min_wear = wear_range[0] if len(wear_range) > 0 else "0"
                    max_wear = wear_range[1] if len(wear_range) > 1 else "1"
                    
                    # 处理价格字段，移除可能的字符串格式化
                    def clean_price(price_str):
                        if isinstance(price_str, (int, float)):
                            return float(price_str)
                        if isinstance(price_str, str):
                            # 移除百分号和空白字符
                            price_str = price_str.strip().rstrip('%')
                            if price_str:
                                try:
                                    return float(price_str)
                                except ValueError:
                                    print(f"警告：无法转换价格 '{price_str}' 为浮点数")
                        return 0.0

                    # 从historical_price_range中提取历史价格范围
                    historical_price_range = item.get('historical_price_range', {})
                    if isinstance(historical_price_range, str):
                        try:
                            historical_price_range = json.loads(historical_price_range)
                        except json.JSONDecodeError:
                            historical_price_range = {}
                    
                    task_data = {
                        'goods_id': int(item.get('template_id', 0)),  # 使用template_id作为goods_id
                        'name': str(item.get('name', '')),  # 饰品名称
                        'hash_name': str(item.get('hash_name', '')),  # 饰品哈希名称
                        'wear': str(item.get('wear', '0-1')),  # 磨损范围
                        'rarity': str(item.get('rarity', '')),  # 稀有度
                        'quality': str(item.get('quality', '')),  # 品质
                        'exterior': str(item.get('exterior', '')),  # 外观
                        
                        # 评分相关字段
                        'score': clean_price(item.get('score', 0)),  # 投资评分
                        'liquidity_score': clean_price(item.get('liquidity_score', 0)),  # 流动性评分
                        'price_advantage_score': clean_price(item.get('price_advantage_score', 0)),  # 价格优势评分
                        'stability_score': clean_price(item.get('stability_score', 0)),  # 稳定性评分
                        'supply_score': clean_price(item.get('supply_score', 0)),  # 供需评分
                        'daily_volume': clean_price(item.get('daily_volume', 0)),  # 日均成交量
                        
                        # 价格相关字段
                        'sell_min_price': clean_price(historical_price_range.get('lowest_price', 0)),  # 历史最低价
                        'sell_max_price': clean_price(historical_price_range.get('highest_price', 0)),  # 历史最高价
                        'suggested_snipe_price': clean_price(item.get('suggested_snipe_price', 0)),  # 建议捡漏价格
                        'theoretical_max_buy_price': clean_price(item.get('theoretical_max_buy_price', 0)),  # 理论最高买入价格
                        'target_sell_price': clean_price(item.get('target_sell_price', 0)),  # 目标售价
                        'price_range_compactness': clean_price(item.get('price_range_compactness', 0)),  # 价格区间紧凑度
                        'volatility': clean_price(item.get('volatility', 0)),  # 波动率
                        
                        # JSON字段
                        'historical_success_rate': json.dumps(item.get('historical_success_rate', {}), ensure_ascii=False),  # 历史成功率
                        'trend_analysis': json.dumps(item.get('trend_analysis', {}), ensure_ascii=False),  # 趋势分析
                        'historical_price_range': json.dumps(item.get('historical_price_range', {}), ensure_ascii=False),  # 历史价格
                        'cluster_analysis': json.dumps(item.get('cluster_analysis', {}), ensure_ascii=False),  # 聚类分析
                        
                        # 其他配置字段
                        'tags': json.dumps([tag.strip() for tag in form_data['tag'].split(',') if tag.strip()], ensure_ascii=False),
                        'filter_conf': json.dumps({
                            'type': 'paintwear',
                            'min_paintwear': min_wear,
                            'max_paintwear': max_wear
                        }, ensure_ascii=False),
                        'buy_num_limit': int(form_data['scan_count']),
                        'min_interval': int(form_data['monitor_freq']),
                        'status': int(form_data['status']),
                        'goods_url': f'https://www.youpin898.com/market/goods-list?listType=10&templateId={item.get("template_id")}&gameId=730',
                        'sell_num': int(float(item.get('count', 0))),  # 在售数量
                        'create_at': current_time,
                        'update_at': int(datetime.now().timestamp()),
                        'buying_num': 0,
                        'disabled': 0,
                        'buy_price_limit': clean_price(item.get('suggested_snipe_price', 0)),  # 使用目标售价作为购买价格限制
                        'update_price_auto': 1,
                        'update_price_conf': json.dumps({
                            'type': 'filter',
                            'normal_ratio': 10,
                            'filter_discount': '85'  # 设置为100%，即不打折
                        }, ensure_ascii=False)
                    }
                    
                    # 打印任务数据，用于调试
                    print(f"正在处理商品 {task_data['goods_id']}")
                    print(f"商品数据: {json.dumps(task_data, ensure_ascii=False, indent=2)}")
                    
                    # 查找是否已存在相同goods_id的任务
                    existing_task = self.task_manager.get_task_by_goods_id(task_data['goods_id'])
                    
                    if existing_task:
                        print(f"更新商品 {task_data['goods_id']} 的任务")
                        # 如果任务已存在，更新任务
                        if self.task_manager.update_task(existing_task['id'], task_data):
                            updated_count += 1
                            print(f"成功更新商品 {task_data['goods_id']} 的任务")
                        else:
                            print(f"更新商品 {task_data['goods_id']} 的任务失败")
                    else:
                        print(f"添加商品 {task_data['goods_id']} 的新任务")
                        # 如果任务不存在，添加新任务
                        task_id = self.task_manager.add_task(task_data)
                        if task_id:
                            added_count += 1
                            print(f"成功添加商品 {task_data['goods_id']} 的新任务，ID: {task_id}")
                        else:
                            print(f"添加商品 {task_data['goods_id']} 的任务失败")
                except Exception as e:
                    print(f"处理商品时出错: {str(e)}")
                    print(f"错误详情: {e.__class__.__name__}: {str(e)}")
                    print(f"商品数据: {item}")
                    import traceback
                    print(traceback.format_exc())
            
            message = []
            if added_count > 0:
                message.append(f"新增{added_count}个任务")
            if updated_count > 0:
                message.append(f"更新{updated_count}个任务")
                
            if message:
                QMessageBox.information(self, "成功", "，".join(message))
                self.accept()
            else:
                QMessageBox.warning(self, "提示", "没有任务被添加或更新")
            
        except Exception as e:
            print(f"保存任务时发生错误: {str(e)}")
            print(f"错误详情: {e.__class__.__name__}: {str(e)}")
            import traceback
            print(traceback.format_exc())
            QMessageBox.critical(self, "错误", f"保存任务时发生错误: {str(e)}")
